﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;

using AnOtherBlog.Core;

namespace AnOtherBlog.AJAX.Admin.Users
{
	public partial class UserEdit : AnOtherBlog.Core.Web.AdminBasePage
	{
		#region Member Variables

		string userName = string.Empty;
		bool isEditMode = false;
		MembershipUser membershipUser = null;

		#endregion

		#region Page Events

		/// <summary>
		/// Handles the Load event of the Page control.
		/// </summary>
		/// <param name="sender">The source of the event.</param>
		/// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
		protected void Page_Load(object sender, EventArgs e)
		{
			//base.LblMsg = this.lblMsg;
			
			try
			{
				userName = Util.GetParameter("userName");
				isEditMode = !string.IsNullOrEmpty(userName);

				SetUserEditProperties();

				if (isEditMode)
				{
					pnlAddUser.Visible = false;
					pnlEditUser.Visible = true;
					membershipUser = Membership.GetUser(userName);
				}
				else
				{
					pnlAddUser.Visible = true;
					Register1.DestinationPageUrl = "~/Admin/Users/UserList.aspx";
					// Usamos un control especial
					//cuwRegister.CreatedUser += new EventHandler(cuwRegister_CreatedUser);
					pnlEditUser.Visible = false;
				}

				if (!Page.IsPostBack)
				{
					BindRoles();
					if (isEditMode)
					{
						if (membershipUser != null)
						{
							txtUserName.Enabled = false;
							txtUserName.Text = membershipUser.UserName;
							txtEmail.Text = membershipUser.Email;
							chkActive.Checked = membershipUser.IsApproved;
						}
						else
						{
							MsgSet(string.Format(Resources.AdminUsers.lblUserNotFound, userName));
							pnlEditUser.Visible = false;
						}
					}
				}
			}
			catch (Exception ex)
			{
				MsgSetCritical(ex.Message);
			}
		}

		/// <summary>
		/// Handles the Click event of the btnSave control.
		/// </summary>
		/// <param name="sender">The source of the event.</param>
		/// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
		protected void btnSave_Click(object sender, EventArgs e)
		{
			try
			{
				if (isEditMode)
				{
					UpdateUser();
				}
			}
			catch (Exception ex)
			{
				MsgSetCritical(ex.Message);
			}
		}

		/// <summary>
		/// Handles the CreatedUser event of the cuwRegister control.
		/// </summary>
		/// <param name="sender">The source of the event.</param>
		/// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
		//void cuwRegister_CreatedUser(object sender, EventArgs e)
		//{
		//  Response.Redirect(string.Format("~/Admin/Users/UserEdit.aspx?userName={0}", cuwRegister.UserName), true);
		//}

		#endregion

		#region Protected Methods

		/// <summary>
		/// Determines whether [is user in role] [the specified role name].
		/// </summary>
		/// <param name="roleName">Name of the role.</param>
		/// <returns>
		/// 	<c>true</c> if [is user in role] [the specified role name]; otherwise, <c>false</c>.
		/// </returns>
		protected bool IsUserInRole(string roleName)
		{
			if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(roleName))
			{
				return false;
			}
			return Roles.IsUserInRole(userName, roleName);
		}

		#endregion

		#region Private Methods

		/// <summary>
		/// Sets the user edit properties.
		/// </summary>
		private void SetUserEditProperties()
		{
			// TODO: lblApplication debería tener el nombre del blog ????
			Page.Title = Resources.AdminUsers.lblApplication + (isEditMode ? Resources.AdminUsers.pnlEditUser : Resources.AdminUsers.pnlAddUser);
		}

		/// <summary>
		/// Binds the roles.
		/// </summary>
		private void BindRoles()
		{
			if (Roles.Enabled)
			{
				rptrRoles.DataSource = Roles.GetAllRoles();
				rptrRoles.DataBind();
			}
		}

		/// <summary>
		/// Updates the user.
		/// </summary>
		private void UpdateUser()
		{
			if (Page.IsValid)
			{
				membershipUser.Email = txtEmail.Text.Trim();
				membershipUser.IsApproved = chkActive.Checked;
				Membership.UpdateUser(membershipUser);
				UpdateRoleMembership();
				MsgSet(Resources.AdminUsers.lblUserUpdated);
			}
			else
			{
				MsgSet(Resources.AdminUsers.lblUserNotUpdated);
			}
		}

		/// <summary>
		/// Updates the role membership.
		/// </summary>
		private void UpdateRoleMembership()
		{
			foreach (RepeaterItem repeaterItem in rptrRoles.Items)
			{
				CheckBox checkBox = repeaterItem.FindControl("checkbox1") as CheckBox;
				if (checkBox != null)
				{
					if (checkBox.Checked && !Roles.IsUserInRole(userName, checkBox.Text))
					{
						Roles.AddUserToRole(userName, checkBox.Text);
					}
					if (!checkBox.Checked && Roles.IsUserInRole(userName, checkBox.Text))
					{
						Roles.RemoveUserFromRole(userName, checkBox.Text);
					}
				}
			}
		}

		#endregion

	}
}
